package com.java.servlet.web.chat.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.java.servlet.web.commons.Chat;
import com.java.servlet.web.commons.PropertiesUtils;

@WebServlet (name = "ChatController", urlPatterns = "/chat/chatController")
public class ChatController extends HttpServlet {
	private static final long serialVersionUID = 6451090012522852262L;
	private static final Logger log = Logger.getLogger(ChatController.class);
	private static final int INIT_CHAT = 0;
	private static final int SEND_CHAT = 1;
	private static final int TIME_CHAT = 2;
	private Properties viewConfig;
	
	
	public ChatController(){
	}
    public void init() {
		try {
			super.init();
			viewConfig = PropertiesUtils.getPropertiesFromFile(getServletContext().getResource("/WEB-INF/view-config.properties"));
		} catch (MalformedURLException ex) {
			log.info("Error fatal, no se puedo cargar el archivo de configuracion de vistas." + ex);
		} catch(ServletException serEx){
			log.info("Error fatal, no se puedo cargar el archivo de configuracion de vistas." + serEx);
		}
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
		int metodo = Integer.parseInt(request.getParameter("method"));
		RequestDispatcher dispatcher = null;
		try {
			switch (metodo) {
			case INIT_CHAT:
				String user = (String)request.getSession().getAttribute("user");
				String uid = new String(user.getBytes("ISO-8859-1"), "UTF-8");
				String newUid = uid;
				int i = 2;
				Map<String, List<String>> chat = Chat.getChatMap();
				synchronized (chat) {
					if ("you".equalsIgnoreCase(newUid))
						newUid = uid + i++;
					while (chat.containsKey(newUid))
						newUid = uid + i++;
					uid = newUid;
					chat.put(uid, new ArrayList<String>());
				}
				dispatcher = request.getRequestDispatcher(viewConfig.getProperty("chat.pagina.form"));
				dispatcher.forward(request, response);
				break;
			case SEND_CHAT:
				log.info("--------------------{SEND_CHAT}---------------------");
				/*
				String uid = (String)request.getSession().getAttribute("UID");
				for (String s : chatList.keySet()) {
					if (!s.equals(uid)) {
						synchronized (chatList.get(s)) {
							// put message to any other user's msg list
							chatList.get(s).add(uid+" said: "+msg);
						}
					}
				}*/
				break;
			case TIME_CHAT:
				log.info("--------------------{SEND_CHAT}---------------------");
				/*String uids = (String)request.getSession().getAttribute("UID");
				if (uids == null)
					response.sendError(HttpServletResponse.SC_BAD_REQUEST);
				List<String> l = chatList.get(uids);
				synchronized (l) {
					if (l.size() > 0) {
						// for UTF-8 chars
						response.setCharacterEncoding("UTF-8");
						PrintWriter outs = response.getWriter();
						JSONArray jsna = new JSONArray();
						// add all msg to json array and clear list
						while (l.size() > 0)
							jsna.add(l.remove(0));
//
						outs.println(jsna);
						outs.close();
					}
				}*/
				break;
			}
		} catch (Exception e) {
			request.setAttribute("ex", e);
            dispatcher = request.getRequestDispatcher(viewConfig.getProperty("error"));
            dispatcher.forward(request, response);
			System.out.println("Error en LoginController " + e);
			e.printStackTrace();
		} finally {
            out.close();
        }
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}
